﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BenzInfo.Hockey.Grenadiers.Models;
using System.Drawing;
using System.Drawing.Imaging;
using BenzInfo.Hockey.Grenadiers.Utils;

namespace BenzInfo.Hockey.Grenadiers.Controllers
{ 
    public class AdsController : BaseController
    {
        private GrenadiersContext db = new GrenadiersContext();

        private const string BASE_PATH = "~/Content/images/posts";

        private const string AdKey = "Ads";

        //
        // GET: /Ad/

        public ViewResult Index()
        {
            List<Ad> ads = db.Ads.Where(p => p.Key == AdKey).ToList();

            if (ads.Count == 0)
            {
                Ad ad = new Ad()
                {
                    Key = AdKey,
                    TitleEN = "Ad",
                    TitleFR = "Publicité",
                    ContentEN = "Ad",
                    ContentFR = "Publicité",
                    UserCreatedBy = ViewBag.CurrentUser,
                    DateCreated = DateTime.Now,
                    UserModifiedBy = ViewBag.CurrentUser,
                    DateModified = DateTime.Now,
                    Link = "http://www.grenadiersdechateauguay.com"
                };

                db.Ads.Attach(ad);
                db.Ads.Add(ad);
                db.SaveChanges();
                ads.Add(ad);
            }

            return View(ads);
        }
        //
        // GET: /Shop/Edit/5
        public ActionResult Add()
        {
            return PartialView();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Add(Ad ad, HttpPostedFileBase inputFile)
        {

            if (inputFile != null)
            {
                using (Image img = Image.FromStream(inputFile.InputStream))
                {
                    string ext = inputFile.FileName.Split('.')[inputFile.FileName.Split('.').Length - 1];
                    string filename = string.Format("{0:000}.{1}", DateTime.Now.Ticks, ext);
                    string filepath = string.Format("{0}/{1}", Server.MapPath(BASE_PATH), filename);

                    ImageHelper.Save(img, filepath, ext);

                    ad.Picture = filename;
                }
            }

            ad.UserCreatedBy = ViewBag.CurrentUser;
            ad.DateCreated = DateTime.Now;
            ad.UserModifiedBy = ViewBag.CurrentUser;
            ad.DateModified = DateTime.Now;
            ad.Key = AdKey;

            ModelState.Remove("UserCreatedBy");
            ModelState.Remove("UserModifiedBy");
            ModelState.Remove("Key");

            if (ModelState.IsValid)
            {
                db.Ads.Attach(ad);
                db.Ads.Add(ad);
                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }         
        //
        // GET: /Ad/Edit/5

        public ActionResult Edit(int id)
        {
            Ad ad = db.Ads.Find(id);

            return PartialView("Edit", ad);
        }

        //
        // POST: /Ad/Edit/5

        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(Ad ad, HttpPostedFileBase inputFile, string nopicture)
        {
            if (nopicture == "on")
            {
                ad.Picture = null;
            }
            else if (inputFile != null)
            {
                using (Image img = Image.FromStream(inputFile.InputStream))
                {
                    string ext = inputFile.FileName.Split('.')[inputFile.FileName.Split('.').Length - 1];
                    string filename = string.Format("{1}_{0:000}.{2}", DateTime.Now.Ticks, ad.Id, ext);
                    string filepath = string.Format("{0}/{1}", Server.MapPath(BASE_PATH), filename);

                    ImageHelper.Save(img, filepath, ext);

                    ad.Picture = filename;
                }
            }

            Ad addb = db.Ads.Find(ad.Id);

            ad.UserModifiedBy = ViewBag.CurrentUser;
            ad.DateModified = DateTime.Now;

            ModelState.Remove("UserCreatedBy");
            ModelState.Remove("UserModifiedBy");

            TryUpdateModel(addb);

            if (ModelState.IsValid)
            {
                addb.Picture = ad.Picture; // Quickfix...
                db.Ads.Attach(addb);
                db.Entry(addb).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return PartialView(ad);
        }
        public ActionResult Delete(int id)
        {
            Ad ad = db.Ads.Find(id);
            db.Ads.Remove(ad);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}